import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { TimeConfigClass } from '../../../../common/common-config';
import { TeaminfoService } from '../teaminfo.service';
import { StorageService } from '../../../../common/storage.service';


@Component({
  selector: 'app-teaminfo',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.css'],
  providers: [TeaminfoService]
})
export class TeaminfoComponent implements OnInit {
  timeConfig: any = new TimeConfigClass(); // 时间空间初始化
  cols; // 表格头部
  colsSelected; // 表格选中的显示列
  pageSize; // 分页大小
  pageNo; // 当前页
  totalRecords; // 数据条数
  listData; // 数据
  billStatus; // 施工队状态
  selectedBillStatus; // 选中后的施工队状态
  cashDepositStatus; // 施工队保证金状态
  selectedCashDepositStatus; // 选中后的施工队保证金状态
  searchObj: any = {}; // 搜索条件
  selectedOrganization: any = {}; // 选中后的所属公司
  selectedRowData = []; // 选中行数据
  organizationArr = []; // 所属公司
  searFlag = true;
  searResult = '您还未添加任何内容';
  paginator = false;
  constructor(private router: Router, private teaminfoService: TeaminfoService, private storage: StorageService) {
    // 表头
    this.cols = [
      { field: 'account', header: '项目经理用户名', width: '100px', frozen: false, sortable: true, tem: true },
      { field: 'foremanName', header: '姓名', frozen: false, sortable: true },
      { field: 'teamName', header: '工队名称', width: '150px', sortable: true },
      { field: 'companyName', header: '所属公司', sortable: true },
      { field: 'billStatusText', header: '状态', sortable: true },
      { field: 'managerTelephone', header: '项目经理手机号', width: '80px',sortable: true },
      { field: 'serviceAreaName', header: '服务区域',sortable: true },
      { field: 'workerNum', header: '工人数量', width: '50px', sortable: true, hidden: true },
      { field: 'ability', header: '施工能力', width: '200px', sortable: true },
      { field: 'cashDepositStatusText', header: '保证金状态', width: '200px', sortable: true },
    ];
    this.colsSelected = this.cols;
    // 获取施工队状态和施工队押金状态并填充到对对应下拉框中
    this.teaminfoService.getStatus().then(
      data => {
        if (data.result) {
          this.billStatus = data.data.billStatus;
          this.cashDepositStatus = data.data.cashDepositStatus;
        } else {
          this.storage.messageService.emit({ severity: 'error', detail: '字典服务异常！' });
        }
      }
    );
    // 施工队表格初始化
    this.teaminfoService.list().then(
      data => {
        if (data.result) {
          this.listData = data.data.list;
          this.totalRecords = data.data.totalCount;
          this.listData.length > 0 ? this.paginator = true : this.paginator = false;
        } else {
          this.listData = [];
          this.totalRecords = 0;
          this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
        }
      }
    );
  }

  ngOnInit() {
    this.getOrganization();
  }

  /**
   * 搜索方法
   */
  search() {
    this.searchObj['sortF'] = "";
    if (this.selectedOrganization && this.selectedOrganization['name'] !== this.organizationArr[0]['name']) {
      this.searchObj['companyName'] = this.selectedOrganization['name'];
    } else {
      delete this.searchObj['companyName'];
    }
    if (this.selectedBillStatus && this.selectedBillStatus.code !== this.billStatus[0].code) {
      this.searchObj['billStatus'] = this.selectedBillStatus.code;
    } else {
      delete this.searchObj['billStatus'];
    }
    if (this.selectedCashDepositStatus && this.selectedCashDepositStatus.code !== this.cashDepositStatus[0].code) {
      this.searchObj['cashDepositStatus'] = this.selectedCashDepositStatus.code;
    } else {
      delete this.searchObj['cashDepositStatus'];
    }

    if (!this.searchObj['searchValue']) {

      delete this.searchObj['searchValue'];
    } else {
      this.searchObj['searchValue'] = this.searchObj['searchValue'].trim();
      if (this.searchObj['searchValue'].length > 20) {
        this.storage.messageService.emit({ severity: 'warn', detail: '工队名称/用户名/手机号/姓名 20个字' });
        return;
      }
    }
    this.pageSize = 20;
    this.pageNo = 1;
    this.storage.loading();
    this.teaminfoService.list(this.searchObj, this.pageSize, this.pageNo).then(
      data => {
        this.storage.loadout();
        if (data.result) {
          this.listData = data.data.list;
          this.totalRecords = data.data.totalCount;
          this.listData.length > 0 ? this.paginator = true : this.paginator = false;
          this.searResult = '未查到想要的数据';
        } else {
          this.listData = [];
          this.totalRecords = 0;
          this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
        }
      }
    );
  }


  /**
  * 获取公司数据
  */
  getOrganization() {
    this.teaminfoService.getOrganization().then(
      data => {
        if (data.result) {
          this.organizationArr = [{ name: '全部' }, ...data.data];
        } else {
          this.storage.messageService.emit({ severity: 'error', detail: '组织机构信息获取异常！' });
        }
      }
    );
  }

  /**
   * dataTable单行选中方法
   * @param event
   */
  onRowSelect(event) {
    if (event.type === 'row') {
      this.router.navigate(['saas/engineer/constructionteam/teaminfo/add']);
    }
  }
  /**
   * 工队详情
   * @param data 工队数据
   */
  info(data) {
    this.router.navigate(['saas/engineer/constructionteam/teaminfo/', data.id]);
  }
  /**
   * dataTable分页查询方法
   * @param event
   */
  onPage(event) {

    this.searchObj['sortF'] = event.sortField;
    this.searchObj['sortO'] = event.sortOrder == 1 ? 'asc' : 'desc';
    if (this.selectedOrganization && this.organizationArr[0] && this.selectedOrganization['name'] !== this.organizationArr[0]['name']) {
      this.searchObj['companyName'] = this.selectedOrganization['name'];
    } else {
      delete this.searchObj['companyName'];
    }

    if (this.selectedBillStatus && this.billStatus[0] && this.selectedBillStatus.code !== this.billStatus[0].code) {
      this.searchObj['billStatus'] = this.selectedBillStatus.code;
    } else {
      delete this.searchObj['billStatus'];
    }
    if (this.selectedCashDepositStatus && this.cashDepositStatus[0] && this.selectedCashDepositStatus.code !== this.cashDepositStatus[0].code) {
      this.searchObj['cashDepositStatus'] = this.selectedCashDepositStatus.code;
    } else {
      delete this.searchObj['cashDepositStatus'];
    }

    if (!this.searchObj['searchValue']) {
      delete this.searchObj['searchValue'];
    } else {
      this.searchObj['searchValue'] = this.searchObj['searchValue'].trim();
      if (this.searchObj['searchValue'].length > 50) {
        this.storage.messageService.emit({ severity: 'warn', detail: '工队名称/用户名/手机号/姓名 50个字符内' });
        return;
      }
    }

    this.pageSize = event.rows;
    const pageTem = parseInt((event.first / event.rows).toString(), 0);
    this.pageNo = pageTem + 1;
    this.storage.loading();
    this.teaminfoService.list(this.searchObj, this.pageSize, this.pageNo).then(
      data => {
        this.storage.loadout();
        this.selectedRowData = [];
        if (data.result) {
          this.listData = data.data.list;
          this.totalRecords = data.data.totalCount;
          this.listData.length > 0 ? this.paginator = true : this.paginator = false;
          this.searResult = '未查到想要的数据';
        } else {
          this.listData = [];
          this.totalRecords = 0;
          this.storage.messageService.emit({ severity: 'error', detail: '操作失败！' });
        }
      }
    );
  }
  /**
   * 创建工队数据
   */
  addTeam() {
    this.router.navigate(['/saas/engineer/constructionteam/teaminfo/add']);
  }

  /**
   * 创建工人
   */
  addWorker() {
    if (this.selectedRowData.length <= 0) {
      this.storage.makesureService.emit({
        message: '请选择要操作的数据！',
        header: '提示',
        rejectVisible: false,
        acceptVisible: false,
        accept: () => {
        }
      });
    } else if (this.selectedRowData.length === 1) {
      this.router.navigate(['/saas/engineer/constructionteam/teaminfo/worker/add', { teamId: this.selectedRowData[0].id }]);
    } else {
      this.storage.makesureService.emit({
        message: '只能勾选一条数据！',
        header: '提示',
        rejectVisible: false,
        acceptVisible: false,
        accept: () => {
        }
      });

    }

  }


  // 禁用提示
  stopOrderTitle() {

  }

  /**
  * Description: 停止接单
  */
  stopOrder() {
    if (this.selectedRowData) {
      let list = this.selectedRowData;
      let ids = new Array();
      for (let index of list) {
        ids.push(index.id);
      }
      if (ids.length === 0) {
        this.nodata();
        return;
      }
      this.storage.makesureService.emit({
        message: '是否确认停止' + ids.length + '个施工队接单？',
        header: '提示',
        rejectLabel: '取消',
        acceptLabel: '确定',
        acceptVisible: true,
        rejectVisible: true,
        accept: () => {
          this.storage.loading();
          this.teaminfoService.updateStatus({ ids: ids.toString() }).then(
            data => {
              this.storage.loadout();
              if (data.result) {
                this.search();
                this.storage.messageService.emit({ severity: 'success', detail: data.msg });
              } else {
                this.storage.messageService.emit({ severity: 'error', detail: data.msg });
              }
              this.selectedRowData = [];
            }
          );
        },
        reject: () => {
          this.selectedRowData = [];
        }
      });
    }
  }

  // 未选择
  nodata() {
    this.storage.makesureService.emit({
      message: '请选择要操作的数据！',
      header: '提示',
      rejectVisible: false,
      acceptVisible: false,
      accept: () => {
      }
    });
  }
}
